<template>
  <div class="audit-container">
    <!-- 审核内容区域 -->
    <el-page-header @back="goBack" />
    <el-card class="audit-content">
      <template #header>
        <div class="card-header">
          <span class="title">待审核内容</span>
        </div>
      </template>
      
      <el-descriptions :column="1" border>
        <el-descriptions-item label="项目名称">{{ auditData.projectName }}</el-descriptions-item>
        <el-descriptions-item label="项目编号">{{ auditData.projectCode }}</el-descriptions-item>
        <el-descriptions-item label="投资方">{{ auditData.investor }}</el-descriptions-item>
        <el-descriptions-item label="产业类别">
          <el-tag :type="getIndustryTagType(auditData.industryCategory)">
            {{ auditData.industryCategory }}
          </el-tag>
        </el-descriptions-item>
       <el-descriptions-item label="上传文件">
<div class="file-list">
  <div v-for="file in auditData.files" :key="file.id" class="file-item">
    <el-icon><Document /></el-icon>
    <span class="file-name">{{ file.name }}</span>
    <span class="file-size">({{ formatFileSize(file.size) }})</span>
    <el-button type="text" size="small" @click="downloadFile(file)">下载</el-button>
  </div>
</div>
</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 审核记录区域 -->
    <el-card class="audit-records">
      <template #header>
        <div class="card-header">
          <span class="title">审核记录</span>
        </div>
      </template>
      
       <!-- 空状态判断 -->
      <el-empty 
      v-if="auditRecords.length === 0"
      description="暂无审核记录"
      :image-size="100"
      />

      <el-timeline>
        <el-timeline-item
          v-for="(record, index) in sortedAuditRecords"
          :key="index"
          :timestamp="formatDateTime(record.time)"
          :type="getRecordType(record.status)"
          :color="getRecordColor(record.status)"
          placement="top"
        >
          <el-card>
            <h4>{{ record.auditor }} - {{ record.department }}</h4>
            <p>{{ record.comment || '无审核意见' }}</p>
            <div class="record-status">
              <el-tag :type="getRecordType(record.status)">
                {{ record.status }}
              </el-tag>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>

    <!-- 上传文件区域 -->
    <div class="white-container" v-if="getDisplayAreas.showUpload">
        <div class="card-header">
          <span class="title">文件上传</span>
        </div>
        <el-divider />
        
        <el-upload
          class="upload-area"
          action="#"
          multiple
          :limit="5"
          :file-list="contractFiles"
          :auto-upload="false"
          :on-change="handleFileChange"
          :on-remove="handleRemove"
          :on-exceed="handleExceed"
          drag
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            拖拽文件到此处或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持上传PDF、Word文档，单个文件不超过10MB
            </div>
          </template>
        </el-upload>

         <el-button 
          type="primary" 
          size="large"
          @click="handleApply"
          class="apply-button"
        >
          提交
        </el-button>
    </div>

    <!-- 审核意见区域 -->
    <div class="audit" v-if="getDisplayAreas.showOpinion">
    <el-card class="audit-opinion" >
      <template #header>
        <div class="card-header">
          <span class="title">审核意见</span>
          <span class="required">*</span>
        </div>
      </template>
      
      <el-input
        v-model="auditComment"
        type="textarea"
        :rows="4"
        placeholder="请输入审核意见（必填）"
        clearable
      />
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button
        type="success"
        size="large"
        @click="handleApprove"
        :disabled="!auditComment"
      >
        <el-icon><CircleCheck /></el-icon>
        通过
      </el-button>
      
      <el-button
        type="danger"
        size="large"
        @click="handleReject"
        :disabled="!auditComment"
      >
        <el-icon><CircleClose /></el-icon>
        驳回
      </el-button>
    </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed,watch } from 'vue'
import { Document, CircleCheck, CircleClose, UploadFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { useProjectStore } from '@/stores/project'
import axios from 'axios'
// API基础URL（从环境变量获取，自动适配环境）
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
const projectStore = useProjectStore()
const router = useRouter()
const route = useRoute()

const auditRecords = ref([])
const auditData = ref({})
const auditComment = ref('')
const contractFiles = ref([])
const uploadedFiles = ref([])
const loading = ref(false)

// 获取项目ID（从query参数获取）
const projectId = ref(route.query.projectId || null)
// 从路由参数获取当前步骤和部门
const currentStep = ref(parseInt(route.query.currentStep) || 1)
const currentDepartment = ref(route.query.department || '')

// 获取项目数据
const fetchProjectData = async () => {
  if (!projectId.value) return
  
  loading.value = true
  try {
    const response = await axios.get(`${API_BASE_URL}/api/projects/${projectId.value}`)
    auditData.value = response.data
    console.log('API返回的项目数据:', response.data) // 添加这行来查看完整的数据结构
  } catch (error) {
    console.error('获取项目数据失败:', error)
    ElMessage.error('获取项目数据失败')
  } finally {
    loading.value = false
  }
}

// 获取审核记录的方法
const fetchAuditRecords = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/projects/${projectId.value}/audit-records`)
    auditRecords.value = response.data
  } catch (error) {
    console.error('获取审核记录失败:', error)
    ElMessage.error('获取审核记录失败')
  }
}

// 新增审核记录
const addAuditRecord = async (recordData) => {
  try {
    const response = await axios.post(`${API_BASE_URL}/api/projects/${projectId.value}/audit-records`, recordData)
    return response.data
  } catch (error) {
    console.error('新增审核记录失败:', error)
    throw error
  }
}

const goBack = () => {
  router.go(-1)
}

// 文件大小格式化
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取产业类别标签类型
const getIndustryTagType = (category) => {
  const map = {
    '智能制造': '',
    '电子信息': 'success',
    '生物医药': 'warning',
    '新能源': 'danger',
    '新材料': 'info'
  }
  return map[category] || ''
}

// 获取记录类型
const getRecordType = (status) => {
  const map = {
    '已通过': 'success',
    '已驳回': 'danger',
    '审核中': 'warning'
  }
  return map[status] || ''
}

// 获取记录颜色
const getRecordColor = (status) => {
  const map = {
    '已通过': '#67C23A',
    '已驳回': '#F56C6C',
    '审核中': '#E6A23C'
  }
  return map[status] || ''
}

const downloadFile = (file) => {
  if (file.raw) {
    // 如果是新上传的文件，创建下载链接
    const link = document.createElement('a')
    link.href = URL.createObjectURL(file.raw)
    link.download = file.name
    link.click()
    URL.revokeObjectURL(link.href)
  } else {
    // 实际项目中这里应该调用文件下载API
    ElMessage.info(`下载文件: ${file.name}`)
    // window.open(`/api/files/download/${file.id}`, '_blank')
  }
}

// 按ID倒序排列的审核记录
const sortedAuditRecords = computed(() => {
  return [...auditRecords.value].sort((a, b) => b.id - a.id)
})

// 格式化时间为 YYYY-MM-DD HH:mm:ss
const formatDateTime = (timeString) => {
  const date = new Date(timeString)
  if (isNaN(date.getTime())) return timeString // 如果解析失败，返回原字符串
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 通过审核
const handleApprove = async () => {
  ElMessageBox.confirm('确认通过该项目的审核吗？', '审核确认', {
    confirmButtonText: '确认通过',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用后端接口新增审核记录
      await addAuditRecord({
        status: '已通过',
        auditor: '当前用户', // 实际项目中应从用户信息获取
        department: currentDepartment.value,
        comment: auditComment.value,
        time: new Date().toISOString(),
        step: currentStep.value
      })

      ElMessage.success(`文件已通过,当前审核步骤:${currentStep.value}`)
      auditComment.value = ''
      
      // 刷新审核记录
      await fetchAuditRecords()
      
      router.go(-1)
    } catch (error) {
      ElMessage.error('审核操作失败')
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 拒绝审核
const handleReject = async () => {
  ElMessageBox.confirm('确认驳回该项目的审核吗？', '审核确认', {
    confirmButtonText: '确认驳回',
    cancelButtonText: '取消',
    type: 'warning',
    inputPlaceholder: '请输入驳回理由（可选）',
    inputValidator: (val) => {
      if (!val && !auditComment.value) {
        return '驳回理由不能为空'
      }
      return true
    }
  }).then(async ({ value }) => {
    const rejectReason = value || auditComment.value

    try {
      // 调用后端接口新增审核记录
      await addAuditRecord({
        status: '已驳回',
        auditor: '当前用户',
        department: currentDepartment.value,
        comment: rejectReason,
        time: new Date().toISOString(),
        step: currentStep.value
      })

      ElMessage.success(`文件已驳回,当前审核步骤:${currentStep.value}`)
      auditComment.value = ''
      
      // 刷新审核记录
      await fetchAuditRecords()
      
      router.go(-1)
    } catch (error) {
      ElMessage.error('驳回操作失败')
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 文件上传处理
const handleFileChange = (file, fileList) => {
  // 检查文件大小
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB')
    return false
  }
  
  // 检查文件名是否重复
  const isDuplicate = fileList.some(f => 
    f.name === file.name && 
    f.uid !== file.uid
  )
  
  if (isDuplicate) {
    ElMessage.error(`文件 "${file.name}" 已存在`)
    return false
  }
  
  // 添加到文件列表
  contractFiles.value = fileList.map(file => ({
    name: file.name,
    size: file.size,
    type: file.name.split('.').pop() || 'file',
    raw: file.raw,
    url: URL.createObjectURL(file.raw)
  }))
  
  return true
}

// 移除文件
const handleRemove = (file, fileList) => {
  contractFiles.value = fileList.map(file => ({
    name: file.name,
    size: file.size,
    type: file.type.split('/')[1] || file.type,
    raw: file.raw,
    url: URL.createObjectURL(file.raw)
  }))
}

// 超出限制
const handleExceed = () => {
  ElMessage.warning('最多只能上传5个文件')
}

const handleApply = async () => {
  if (contractFiles.value.length === 0) {
    ElMessage.warning('请先上传文件')
    return
  }
  
  ElMessageBox.confirm('确认提交这些文件吗？', '文件提交确认', {
    confirmButtonText: '确认提交',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const fileNames = contractFiles.value.map(f => f.name).join('、')

    try {
      // 调用后端接口新增审核记录
      await addAuditRecord({
        status: '已提交',
        auditor: '当前用户',
        department: currentDepartment.value,
        comment: `提交文件：${fileNames}`,
        time: new Date().toISOString(),
        step: currentStep.value
      })

      ElMessage.success(`成功提交文件，当前审核步骤:${currentStep.value}`)
      contractFiles.value = [] // 清空上传列表
      
      // 刷新审核记录
      await fetchAuditRecords()
      
      router.go(-1)
    } catch (error) {
      ElMessage.error('文件提交失败')
    }
  }).catch(() => {
    ElMessage.info('已取消提交')
  })
}

// 统一判断显示区域的函数 - 修复版本
const getDisplayAreas = computed(() => {

  const projectType = auditData.value.projectType
  const projectState = auditData.value.state
  
  console.log('项目类型:', projectType, '项目状态:', projectState, '当前步骤:', currentStep.value)
  
  // 租赁厂房项目 - 建设中状态
  if (projectType === 'rental' && projectState === 'construction') {
    return {
      showUpload: false,
      showOpinion: true
    }
  }
  // 租赁厂房项目 - 竣工投产状态
  if (projectType === 'rental' && projectState === 'completion') {
    return {
      showUpload: currentStep.value === 1,
      showOpinion: currentStep.value === 2
    }
  }
  
  // 独立选址项目 - 征地报批状态
  if (projectType === 'independent' && projectState === 'landApproval') {
    return {
      showUpload: [1, 2, 3, 4, 6, 8].includes(currentStep.value),  
      showOpinion: [5, 7].includes(currentStep.value)          
    }
  }
  
  // 独立选址项目 - 竣工投产状态
  if (projectType === 'independent' && projectState === 'completion') {
    return {
      showUpload: currentStep.value === 1,
      showOpinion: [2, 3, 4].includes(currentStep.value)
    }
  }

  // 独立选址项目 - 建设中状态（默认）
  if (projectType === 'independent') {
    return {
      showUpload: [1, 2, 3, 5].includes(currentStep.value),
      showOpinion: [4, 6].includes(currentStep.value)
    }
  }

  // 默认情况
  return {
    showUpload: false,
    showOpinion: false
  }
})

// 添加调试信息
watch(getDisplayAreas, (newValue) => {
  console.log('显示区域变化:', newValue)
})

onMounted(async () => {
  if (projectId.value) {
    await fetchProjectData()
    await fetchAuditRecords()
    console.log('初始化完成:', {
      projectId: projectId.value,
      currentStep: currentStep.value,
      department: currentDepartment.value,
      projectData: auditData.value,
      displayAreas: getDisplayAreas.value
    })
  }
})
</script>

<style scoped>
.audit-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  align-items: center;
}

.card-header .title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.card-header .required {
  color: #F56C6C;
  margin-left: 5px;
}

.audit-content,
.audit-records,
.audit-opinion {
  margin-bottom: 20px;
}

.file-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-name {
  flex: 1;
}

.file-size {
  color: #909399;
  font-size: 12px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin-top: 30px;
}

.action-buttons .el-button {
  width: 180px;
  height: 50px;
  font-size: 16px;
}

.action-buttons .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.record-status {
  margin-top: 10px;
}

/* 文件上传 */
.white-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.upload-area {
  width: 400px;
  height: 280px;
  margin-bottom:10px;
  margin-top: 50px;
  margin-left: 330px;
}

:deep(.el-upload-dragger) {
  padding: 40px;
  border-radius: 8px;
}

:deep(.el-icon--upload) {
  font-size: 67px;
  color: #c0c4cc;
  margin: 40px 0 16px;
  line-height: 50px;
}

:deep(.el-upload__text) {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

:deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
}

:deep(.el-upload__tip) {
  margin-top: 15px;
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.uploaded-files-list {
  margin-top: 20px;
}

.apply-button {
  width: 100px;
  height: 40px;
  font-size: 15px;
  margin: 30px auto;
  display: block;
}


</style>